package net.esj.basic.plugins.richtext;

import java.io.File;
import java.io.IOException;

import net.esj.basic.core.engine.support.MelonSupporter;
import net.esj.basic.core.engine.tools.rule.FileRule;
import net.esj.basic.exception.MelonRuntimeException;
import net.esj.basic.utils.Validators;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;

public class FileRichText implements RichText<File> {

	private static final Logger log        = org.apache.log4j.Logger.getLogger(FileRichText.class);
	
	private FileRule fileRule;

	private String filename;
	
	private String content;
	
	public FileRichText(FileRule fileRule,String filename) {
		super();
		this.fileRule = fileRule;
		this.filename = filename;
	}

	@Override
	public File getText() {
		File file = new File(fileRule.getRootPath()+filename);
		return file;
	}

	@Override
	public String loadToString() {
		try {
			return FileUtils.readFileToString(getText(), MelonSupporter.SYS_ENCODING);
		} catch (IOException e) {
			log.debug("读文件出错", e);
		}
		return "";
	}

	@Override
	public File setText(String content) {
		if(fileRule==null){
			throw new MelonRuntimeException("规则不存在，请先设置规则");
		}
		try {
			File file = new File(fileRule.getAbsolutePath());
			if(Validators.isEmpty(content)){
				file.createNewFile();
			}else{
				FileUtils.writeStringToFile(file, content, MelonSupporter.SYS_ENCODING);
			}
			return file;
		} catch (IOException e) {
			log.debug("写文件出错", e);
		}
		return null;
	}
	
	@Override
	public void deleteText() {
		File f = getText();
		f.deleteOnExit();
	}

	public FileRule getFileRule() {
		return fileRule;
	}

	public void setFileRule(FileRule fileRule) {
		this.fileRule = fileRule;
	}

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

}
